import { login, logout, getInfo, refreshToken, userCache, validPortalFrontUrl, agencies, org } from '@/api/user'
// import { getToken, setToken, removeToken } from '@/utils/auth'
import { encryption } from '@/utils/index'
import { getStore, setStore } from '@/utils/store'
import { getToken, setToken, removeToken, setAccount, setUserInfo, removeUserInfo } from '@/utils/auth'

const state = {
  token: getToken(),
  expires_in: getStore({
    name: 'expires_in'
  }) || '',
  refresh_token: getStore({
    name: 'refresh_token'
  }) || '',
  name: '',
  permissions: {},
  user: {},
  userCache: {}, // 用户缓存信息
  // 缓存路由权限验证结果
  permissionCache: {},
  agencies: [], // 职员信息
  org: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, user) => {
    state.user = user
    setUserInfo(user)
  },
  // SET_PERMISSIONS: (state, permissions) => {
  //   const list = {}
  //   for (let i = 0; i < permissions.length; i++) {
  //     list[permissions[i]] = true
  //   }
  //   state.permissions = list
  // },
  // FIX: 当用户关闭标签页，过一段时间再打开标签页，造成刷新时机不对的错误
  SET_EXPIRES_IN: (state, expires_in) => {
    if (expires_in) {
      expires_in = (new Date().getTime()) / 1000 + expires_in - (10 * 60) // 提前10分钟刷新
    }
    state.expires_in = expires_in
    setStore({
      name: 'expires_in',
      content: state.expires_in
    })
  },
  SET_REFRESH_TOKEN: (state, rfToken) => {
    state.refresh_token = rfToken
    setStore({
      name: 'refresh_token',
      content: state.refresh_token
    })
  },
  SET_USER_CACHE: (state, v) => {
    state.userCache = v
  },
  SET_AGENCIES: (state, v) => {
    state.agencies = v
  },
  SET_ORG: (state, v) => {
    state.org = v
  },
  SET_PERMISSION_CACHE: (state, { pc, res } = {}) => {
    state.permissionCache[pc] = res
  },
  SET_RESET_PERMISSION_CACHE: (state) => {
    state.permissionCache = {}
  }
}

const actions = {

  // user login
  login({ commit, dispatch }, userInfo) {
    setAccount('')
    if (getStore({ name: 'account_name' }) && getStore({ name: 'account_name' }) !== userInfo.username) {
      setStore({
        name: 'moudelId',
        content: ''
      })
    }
    const user = userInfo.isAes ? userInfo : encryption({
      data: userInfo,
      key: 'quanyou,qupcloud',
      param: ['password']
    })
    return new Promise((resolve, reject) => {
      login(user.username, user.password, user.code, user.randomStr).then(response => {
        if (response.data && response.data.access_token) {
          const data = response.data
          commit('SET_TOKEN', data.access_token)
          commit('SET_REFRESH_TOKEN', data.refresh_token)
          commit('SET_EXPIRES_IN', data.expires_in)
          setStore({
            name: 'account_name',
            content: user.username
          })
          setToken(data.access_token)
          setAccount(user.username)
          resolve()
        } else {
          reject('未获取到登录凭证')
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      dispatch('getUserCache')
      dispatch('getAgencies')
      dispatch('getOrg')
      getInfo(state.token).then(response => {
        const data = response.data || {}

        if (!data || !data.userId) {
          reject('验证失败，请重新登录')
        }
        commit('SET_USERINFO', data)
        // dispatch('getUserCache')
        // commit('SET_PERMISSIONS', permissions)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 刷新token
  RefreshToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      refreshToken(state.refresh_token).then(response => {
        const data = response
        commit('SET_TOKEN', data.access_token)
        commit('SET_REFRESH_TOKEN', data.refresh_token)
        commit('SET_EXPIRES_IN', data.expires_in)
        setToken(data.access_token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('menu/SET_MENULIST', [], { root: true })
        // commit('SET_PERMISSIONS', [])
        commit('SET_USERINFO', {})
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_EXPIRES_IN', '')
        commit('SET_RESET_PERMISSION_CACHE')
        removeToken()
        removeUserInfo()
        resolve()
      }).catch(error => {
        removeToken()
        removeUserInfo()
        location.reload()
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('menu/SET_MENULIST', [], { root: true })
      // commit('SET_PERMISSIONS', [])
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_EXPIRES_IN', '')
      removeToken()
      removeUserInfo()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'
      commit('SET_TOKEN', token)
      setToken(token)
      await dispatch('menu/getPortalMenu', '', { root: true })
      resolve()
    })
  },
  // 获取用户缓存信息
  getUserCache({ commit }) {
    userCache().then(res => {
      commit('SET_USER_CACHE', res.data)
      const agentid = res.data.platformNo
      commit('SET_AGENT_ID', agentid, { root: true })
    })
  },
  // 获取办事处信息
  getAgencies({ commit }) {
    agencies().then(res => {
      commit('SET_AGENCIES', res.data)
    })
  },

  // 获取组织信息
  getOrg({ commit }) {
    org().then(res => {
      commit('SET_ORG', res.data)
    })
  },

  // 检测指定页面是否具有访问权限
  validFrontUrl({ commit, state }, { frontUrl, menuCode }) {
    // permissionCache
    const pc = `${frontUrl}`
    if (state.permissionCache.hasOwnProperty(pc)) {
      return Promise.resolve(state.permissionCache[pc])
    }
    return validPortalFrontUrl({ frontUrl, menuCode }).then(res => {
      if (res.success === 1) {
        commit('SET_PERMISSION_CACHE', { pc, res })
        return Promise.resolve(res)
      } else {
        return Promise.reject('无访问权限')
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
